package com.mxsoft.web.filter;

import com.mxsoft.util.ThreadContext;
import com.mxsoft.web.bean.UserObj;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class UserFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {


    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        try {
            UserObj user = ThreadContext.getUser();
            if (null == user) {
                ThreadContext.bindUser(new UserObj("userTest"));
            }

            chain.doFilter(request, response);
        } finally {
            // ThreadLocal的生命周期不等于一次reques请求的生命周期
            // 每个request请求的响应是tomcat从线程池中分配的线程，线程会被下个请求复用
            // 所以请求结束后必须删除线程本地变量
//            ThreadContext.unbindUser();
        }
    }

    @Override
    public void destroy() {
    }
}
